package hu.debrecen.adastra.card.util;

import hu.debrecen.adastra.card.repository.domain.Account;
import hu.debrecen.adastra.card.service.SocialUserService;
import hu.debrecen.adastra.card.web.domain.UserSocialReference;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

public class SignInUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(SignInUtils.class);

	/**
	 * Programmatically signs in the user with the given the user ID.
	 *
	 * @param httpSession
	 */
	public static void signin(final AuthenticationManager authenticationManager, final String userId) {
		SignInUtils.LOGGER.debug("signin: {}", userId);
		Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userId, userId, Lists.newArrayList(new SimpleGrantedAuthority("ROLE_USER"))));
		SecurityContextHolder.getContext().setAuthentication(authentication);
	}

	public static UserSocialReference getUserSocialReference(final SocialUserService socialUserService) {

		Preconditions.checkNotNull(SecurityContextHolder.getContext().getAuthentication(), "Authentication must not be null!");
		Preconditions.checkState(SecurityContextHolder.getContext().getAuthentication().isAuthenticated(), "User must be authenticated!");

		String name = SecurityContextHolder.getContext().getAuthentication().getName();
		SignInUtils.LOGGER.debug("Resolve account by name({})", name);
		Account account = socialUserService.getAccount(name);
		SignInUtils.LOGGER.debug("Resolve userSocialReference by account({})", account.getUsername());

		return socialUserService.getUserSocialReference(account);
	}

}
